'use strict';
const { Service } = require('ee-core');
const { resFail, resOk } = require("../utils/tools");
const Storage = require('ee-core/storage');
const Log = require("ee-core/log");
const { saveFileStreamToLocal, target, flattenTree } = require("../utils/fileTools");
const {
	readDirectory, clearDirectory, recursivelyExtractZips, deleteZipFiles, deleteFiles
} = require("../utils/zip");
const { generateTree } = require("../utils/util");
const { v4: uuidv4 } = require('uuid');
const path = require("path");
const { analyze } = require("../utils/analysis");
const { sleep } = require("ee-core/utils/helper");

class userService extends Service {
	constructor (props) {
		// super(props);
		// this.jsonFile = 'user';
		// this.userDB = Storage.connection(this.jsonFile);
		// this.key = 'user'
		// this.valiDeptNull()
	}

	/**
	 * 数据库为空
	 * @returns {[{name: string, id: string}]}
	 */
	valiDeptNull () {
		if (!this.userDB.db.has(this.key).value()) {
			this.userDB.db.set(this.key, []).write();
		}
	}

	// 获取所有人员
	async getAllUser (params = {}) {
		let { deptId } = params;
		if (!deptId) {
			let data = this.userDB.db
				.get(this.key)
				.value();
			return resOk(data)
		} else {
			let data = this.userDB.db.get(this.key).filter({ deptId }).value();
			return resOk(data)
		}
	}


	async singleFileUpload (params) {
		try {
			const { file, path, single, fileName, deptId } = params;
			let res = await saveFileStreamToLocal(file, path, fileName);
			let user = {
				id: uuidv4().replace(/-/g, '').substring(0, 13), filePath: res, deptId: deptId, name: fileName.split('.')[0]
			}
			this.userDB.db.get(this.key).push(user).write();
			return resOk()
		} catch (e) {
			Log.error(e);
			return resFail()
		}
	}

	async zipFileUpload (params) {
		try {
			const { file, single, fileName, deptId, deptPath } = params;
			await deleteFiles(params.path)
			let res = await saveFileStreamToLocal(file, params.path, fileName);
			await recursivelyExtractZips(target, false)
			await deleteZipFiles()
			await sleep(3000)
			let files = await readDirectory(params.path + '/' + fileName.split('.')[0]);
			let nameMap = {}
			this.userDB.db.get(this.key).remove({
				deptId
			}).write()
			for (let i = 0; i < files.length; i++) {
				let f = files[i];
				let name = f.split('.')[0]
				let type = f.split('.')[1]
				// 获取相关user
				if (!nameMap[name] && type && !type.includes('zip')) {
					let user = {
						id: uuidv4().replace(/-/g, '').substring(0, 13),
						filePath: params.path + '/' + fileName.split('.')[0] + '/' + f,
						deptId: deptId,
						name: name
					}
					this.userDB.db.get(this.key).push(user).write();
					nameMap[name] = true
				}
			}
			return resOk()
		} catch (e) {
			Log.error(e);
			return resFail()
		}
	}

	async uploadAllFile (params) {
		const { file, fileName } = params;
		clearDirectory(target)
		let res = await saveFileStreamToLocal(file, target, fileName);
		await recursivelyExtractZips(target)
		await deleteZipFiles()
		let data = generateTree(target)
		let orgTree = data.orgTree
		let user = data.users
		this.userDB.db.set(this.key, user).write();
		let treeData = flattenTree(orgTree)
		treeData.forEach(tree => {
			if (tree.children) {
				delete tree.children
			}
		})
		return resOk(treeData)
	}

	async uploadBatchFile (params) {
		const { file, fileName, deptPath } = params;
		await clearDirectory(deptPath)
		Log.info('[preload] uploadBatchFile()', deptPath);
		// return {}
		let res = await saveFileStreamToLocal(file, deptPath, fileName);
		await recursivelyExtractZips(deptPath)
		await deleteZipFiles()
		let data = generateTree(target)
		let orgTree = data.orgTree
		let user = data.users
		this.userDB.db.set(this.key, user).write();
		let treeData = flattenTree(orgTree)
		treeData.forEach(tree => {
			if (tree.children) {
				delete tree.children
			}
		})
		return resOk(treeData)
	}

	async analysisWord () {
		let userList = this.userDB.db.get(this.key).value()
		for (let i = 0; i < userList.length; i++) {
			let user = userList[i]
			try {
				if (!user.gender) {
					// TODO 解析文件
					// docx 路径
					let s = user.filePath.split('.')[1]
					let info = null
					if (!s.includes('zip')) {
						if (s === 'docx') {
							info = await analyze(user.filePath)
						} else {
							info = await analyze(user.filePath + 'x')
						}
						this.userDB.db.get(this.key).find({
							id: user.id,
						}).assign({
							...user, ...info
						}).write();
					}
				}
			} catch (e) {
				Log.error(e);
			}
		}
		return resOk()
	}

	async refresh () {
		let data = generateTree(target) // 组织树
		let orgTree = data.orgTree
		let user = data.users
		this.userDB.db.set(this.key, user).write();
		let treeData = flattenTree(orgTree)
		treeData.forEach(tree => {
			if (tree.children) {
				delete tree.children
			}
		})
		return resOk(treeData)
	}
}

userService.toString = () => '[class userService]';
module.exports = userService;
